package com.example.mobile203zlw20216061300618;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Users>list=new ArrayList<>();
    private TextView tvmainTitle;
    private RecyclerView reMainUsers;
    private Button button;
    MySQLiteOpenHelper mySQList;
    SQLiteDatabase database;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        sqlist();
        UsersRViewAdapter usersRViewAdapter=new UsersRViewAdapter(list);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        reMainUsers.setAdapter(usersRViewAdapter);
        main_an_niu();
        reMainUsers.setLayoutManager(linearLayoutManager);
    }
    private void sqlist() {
        mySQList=new MySQLiteOpenHelper(this,"users.db",null,1);//上下文,文件名，厂房，版本号
        database=mySQList.getWritableDatabase();//读写权限任你调
        Cursor cursor=database.query("users",null,null,null,null ,
                null ,null,null);
        if (cursor.moveToFirst()){
            do {
                // 返回列名为columnName对应的列索引（索引从0开始），如果不存在返回-1
                int id=cursor.getInt(cursor.getColumnIndex("_id"));//简称索引
                String name=cursor.getString(cursor.getColumnIndex("name"));
                int age=cursor.getInt(cursor.getColumnIndex("age"));
                list.add(new Users(id,0,name,age));
            }while (cursor.moveToNext());
        }
        cursor.close();
        database.close();
    }
    public void tianjia(View view) {
        View view_2= LayoutInflater.from(MainActivity.this).inflate(R.layout.main_kuang,null);
        tvmainTitle = (TextView) findViewById(R.id.tvmainTitle);
        reMainUsers = (RecyclerView) findViewById(R.id.reMainUsers);
        button = (Button) findViewById(R.id.button);
        new AlertDialog.Builder(this).setTitle("添加数据").setView(view_2)
                .setPositiveButton("添加",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name=((EditText)view_2.findViewById(R.id.edname)).getText().toString();
                                int age=Integer.parseInt(((EditText)view_2.findViewById(R.id.edage)).getText().toString());
                                float score= Float.parseFloat(((EditText)view_2.findViewById(R.id.edscore)).getText().toString());
                                //ContentValues类和Bundle类很类似
                                ContentValues values=new ContentValues();
                                values.put("name",name);
                                values.put("age",age);
                                values.put("score",score);
                                database=mySQList.getWritableDatabase();
                                database.insert("users",null,values);
                                list.clear();
                                Cursor cursor=database.query("users",null,null,null,null,
                                        null,null);
                                if (cursor.moveToFirst()){
                                    do {
                                        // 返回列名为columnName对应的列索引（索引从0开始），如果不存在返回-1
                                        int id=cursor.getInt(cursor.getColumnIndex("_id"));//简称索引
                                        name=cursor.getString(cursor.getColumnIndex("name"));
                                        age=cursor.getInt(cursor.getColumnIndex("age"));
                                        score=cursor.getFloat(cursor.getColumnIndex("score"));
                                        list.add(new Users(age,score, name, id));
                                    }while (cursor.moveToNext());
                                }
                                reMainUsers.getAdapter().notifyDataSetChanged();
                                database.close();
                                cursor.close();
                            }
                        }).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }
    private void main_an_niu(){
        ((UsersRViewAdapter)reMainUsers.getAdapter()).setClickInterface(new UsersRViewAdapter.OnClickInterface() {
            @Override
            public void onclick(View view, int position) {

                switch (view.getId()){
                    case R.id.Delete:
                        database=mySQList.getWritableDatabase();
                        database.delete("users","_id=?",new String[]{String.valueOf(list.get(position).get_id())});
                        list.clear();
                        Cursor cursor=database.query("users",null,null,null,null,
                                null,null);
                        if (cursor.moveToFirst()){
                            do {
                                // 返回列名为columnName对应的列索引（索引从0开始），如果不存在返回-1
                                int id=cursor.getInt(cursor.getColumnIndex("_id"));//简称索引
                                String name=cursor.getString(cursor.getColumnIndex("name"));
                                int age=cursor.getInt(cursor.getColumnIndex("age"));
                                float score=cursor.getFloat(cursor.getColumnIndex("score"));
                                list.add(new Users(id, score, name, age));
                            }while (cursor.moveToNext());
                        }
                        //notifyDataSetChanged()可以在修改适配器绑定的数组后，不用重新刷新Activity
                        reMainUsers.getAdapter().notifyDataSetChanged();
                        database.close();
                        cursor.close();
                        break;
                    case R.id.Update:
                        View view_2= LayoutInflater.from(MainActivity.this).inflate(R.layout.main_kuang,null);
                        view_2.findViewById(R.id.edname);
                        view_2.findViewById(R.id.edage);
                        new AlertDialog.Builder(MainActivity.this).setTitle("更新数据").setView(view_2)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).setPositiveButton("更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name=((EditText)view_2.findViewById(R.id.edname)).getText().toString();
                                int age=Integer.parseInt(((EditText)view_2.findViewById(R.id.edage)).getText().toString());

                                //ContentValues类和Bundle类很类似
                                ContentValues values=new ContentValues();
                                values.put("name",name);
                                values.put("age",age);
                                database=mySQList.getWritableDatabase();
                                database.update("users",values,"_id=?",
                                        new String[]{String.valueOf(list.get(position).get_id())});
                                list.clear();
                                Cursor cursor=database.query("users",null,null,null,null,
                                        null,null);
                                if (cursor.moveToFirst()){
                                    do {
                                        // 返回列名为columnName对应的列索引（索引从0开始），如果不存在返回-1
                                        int id=cursor.getInt(cursor.getColumnIndex("_id"));//简称索引
                                        name=cursor.getString(cursor.getColumnIndex("name"));
                                         age=cursor.getInt(cursor.getColumnIndex("age"));
                                        float score=cursor.getFloat(cursor.getColumnIndex("score"));
                                        list.add(new Users(id, score, name, age));
                                    }while (cursor.moveToNext());
                                }
                                reMainUsers.getAdapter().notifyDataSetChanged();
                                database.close();
                                cursor.close();
                            }
                        }).create().show();
                        break;
                }
            }
        });
    }
    private void initView() {
        tvmainTitle = (TextView) findViewById(R.id.tvmainTitle);
        reMainUsers = (RecyclerView) findViewById(R.id.reMainUsers);
        button = (Button) findViewById(R.id.button);
    }
}